// 用户信息缓存管理
interface UserInfo {
  userId: string;
  avatar: string;
  name: string;
  favoriteCount: number;
  employmentStatus: string;
  isVerified: boolean;
  phone?: string;
  realName?: string;
  idNumber?: string;
  // 扩展字段
  token?: string;
  openId?: string;
  lastLoginTime?: number;
  isHirePerson: boolean;
}

class UserCache {
  private static instance: UserCache;
  private readonly STORAGE_KEY = 'user_info';
  private readonly TOKEN_KEY = 'user_token';
  
  private constructor() {}
  
  public static getInstance(): UserCache {
    if (!UserCache.instance) {
      UserCache.instance = new UserCache();
    }
    return UserCache.instance;
  }
  
  /**
   * 初始化用户信息（登录后调用）
   */
  public initUserInfo(userInfo: Partial<UserInfo>): boolean {
    try {
      const currentTime = Date.now();
	  console.log('djksafjlkasdf对方水电费',this.getOpenId())
      const fullUserInfo: UserInfo = {
        userId: userInfo.userId || '',
        avatar: userInfo.avatar || '',
        name: userInfo.name || '',
        favoriteCount: userInfo.favoriteCount || 0,
        employmentStatus: userInfo.employmentStatus || '未入职',
        isVerified: Boolean(userInfo.isVerified),
        phone: userInfo.phone || '',
        realName: userInfo.realName || '',
        idNumber: userInfo.idNumber || '',
        token: userInfo.token || '',
        openId: userInfo.openId || this.getOpenId()|| '',
        isHirePerson: Boolean(userInfo.isVerified),
        lastLoginTime: currentTime
      };
      
      // 存储到本地
      uni.setStorageSync(this.STORAGE_KEY, fullUserInfo);
      
      // 如果有token，单独存储
      if (userInfo.token) {
        uni.setStorageSync(this.TOKEN_KEY, userInfo.token);
      }
      
      console.log('用户信息初始化成功:', fullUserInfo);
      return true;
    } catch (error) {
      console.error('用户信息初始化失败:', error);
      return false;
    }
  }
  
  /**
   * 获取用户信息
   */
  public getUserInfo(): UserInfo | null {
    try {
      const userInfo = uni.getStorageSync(this.STORAGE_KEY);
      if (userInfo) {
        // 确保 isVerified 是布尔值
        if (typeof userInfo.isVerified === 'string') {
          userInfo.isVerified = userInfo.isVerified === 'true';
        }
        return userInfo;
      }
      return null;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return null;
    }
  }
  
  /**
   * 更新用户信息（部分更新）
   */
  public updateUserInfo(updates: Partial<UserInfo>): boolean {
    try {
      const currentInfo = this.getUserInfo();
      if (!currentInfo) {
        console.warn('没有找到用户信息，无法更新');
        return false;
      }
      
      const updatedInfo = { ...currentInfo, ...updates };
      
      // 确保 isVerified 是布尔值
      if (updates.hasOwnProperty('isVerified')) {
        updatedInfo.isVerified = Boolean(updates.isVerified);
      }
      
      uni.setStorageSync(this.STORAGE_KEY, updatedInfo);
      
      console.log('用户信息更新成功:', updates);
      return true;
    } catch (error) {
      console.error('更新用户信息失败:', error);
      return false;
    }
  }
  
  /**
   * 更新实名认证信息
   */
  public updateVerificationInfo(realName: string, idNumber: string): boolean {
    // 明文存儲，僅在展示端做脫敏
    return this.updateUserInfo({
      realName,
      idNumber,
      isVerified: true
    });
  }
  
  /**
   * 更新收藏数量
   */
  public updateFavoriteCount(count: number): boolean {
    return this.updateUserInfo({ favoriteCount: count });
  }
  
  /**
   * 更新入职状态
   */
  public updateEmploymentStatus(status: string): boolean {
    return this.updateUserInfo({ employmentStatus: status });
  }
  
  /**
   * 设置openId
   */
  public setOpenId(openId: string): boolean {
    try {
      const currentInfo = this.getUserInfo();
      if (!currentInfo) {
        // 如果没有现有用户信息，创建一个新的
        console.log('没有现有用户信息，创建新的用户信息')
        const initSuccess = this.initUserInfo({ openId });
        
        if (initSuccess) {
          console.log('openId设置成功')
          return true;
        } else {
          console.error('openId设置失败，初始化失败')
          return false;
        }
      } else {
        // 如果有现有用户信息，更新openId
        const success = this.updateUserInfo({ openId });
        if (success) {
          console.log('openId更新成功')
        }
        return success;
      }
    } catch (error) {
      console.error('设置openId失败:', error);
      return false;
    }
  }
  
  /**
   * 获取openId
   */
  public getOpenId(): string | null {
    // 正常模式：从用户信息中获取openId
    const userInfo = this.getUserInfo();
    return userInfo?.openId || null;
    
    // 调试模式（注释掉）
    // return '1234568354382349';
  }
  
  /**
   * 初始化默认用户信息（应用启动时调用）
   */
  public initDefaultUserInfo(): void {
    try {
      const currentInfo = this.getUserInfo();
      if (!currentInfo) {
        console.log('初始化默认用户信息',this.getOpenId())
        this.initUserInfo({
          userId: '',
          avatar: '',
          name: '',
          favoriteCount: 0,
          employmentStatus: '未入职',
          isVerified: false,
          phone: '',
          realName: '',
          idNumber: '',
          token: '',
          openId: this.getOpenId() || '', // 调试用的固定openId
          lastLoginTime: Date.now()
        });
      }
    } catch (error) {
      console.error('初始化默认用户信息失败:', error);
    }
  }
  
  /**
   * 获取用户Token
   */
  public getToken(): string | null {
    try {
      return uni.getStorageSync(this.TOKEN_KEY) || null;
    } catch (error) {
      console.error('获取Token失败:', error);
      return null;
    }
  }
  
  /**
   * 检查是否已登录
   */
  public isLoggedIn(): boolean {
    const userInfo = this.getUserInfo();
    const openId = this.getOpenId();
    return !!(userInfo && openId);
  }
  
  /**
   * 检查是否已实名认证
   */
  public isVerified(): boolean {
    const userInfo = this.getUserInfo();
    return userInfo?.isVerified || false;
  }
  
  /**
   * 清除用户信息（登出时调用）
   */
  public clearUserInfo(): void {
    try {
      uni.removeStorageSync(this.STORAGE_KEY);
      uni.removeStorageSync(this.TOKEN_KEY);
      console.log('用户信息清除成功');
    } catch (error) {
      console.error('清除用户信息失败:', error);
    }
  }
  
  /**
   * 身份证号脱敏处理
   */
  private maskIdNumber(idNumber: string): string {
    if (!idNumber || idNumber.length < 8) return idNumber;
    return idNumber.replace(/(\d{3})\d{11}(\d{4})/, '$1***********$2');
  }
  
  /**
   * 手机号脱敏处理
   */
  public maskPhone(phone: string): string {
    if (!phone || phone.length < 7) return phone;
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }
}

// 导出单例实例
export const userCache = UserCache.getInstance();

// 导出类型
export type { UserInfo }; 